'use client';

import { useState, useEffect } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Plus, Edit, Eye, FileText } from 'lucide-react';
import Link from 'next/link';
import DeleteConfirmDialog from '@/components/DeleteConfirmDialog';

interface BlogPost {
  id: string;
  title: string;
  content: string;
  excerpt: string;
  author: string;
  publishedAt: string;
  updatedAt: string;
  tags: string[];
  status: 'draft' | 'published';
  slug: string;
  coverImage?: string;
}

export default function PostsPage() {
  const [posts, setPosts] = useState<BlogPost[]>([]);
  const [loading, setLoading] = useState(true);
  const [deletingId, setDeletingId] = useState<string | null>(null);

  useEffect(() => {
    const fetchPosts = async () => {
      try {
        const response = await fetch('/api/admin/posts');
        const data = await response.json();
        if (response.ok) {
          setPosts(data.posts || []);
        }
      } catch (error) {
        console.error('获取文章失败:', error);
      } finally {
        setLoading(false);
      }
    };

    fetchPosts();
  }, []);

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'short',
      day: 'numeric'
    });
  };

  const handleDelete = async (postId: string) => {
    setDeletingId(postId);
    try {
      const response = await fetch(`/api/posts/${postId}`, {
        method: 'DELETE',
      });

      if (response.ok) {
        // 删除成功，从列表中移除
        setPosts(posts.filter(post => post.id !== postId));
      } else {
        const errorData = await response.json();
        alert(`删除失败: ${errorData.error || '未知错误'}`);
      }
    } catch (error) {
      console.error('删除文章失败:', error);
      alert('删除文章失败，请稍后重试');
    } finally {
      setDeletingId(null);
    }
  };

  if (loading) {
    return (
      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <div>
            <h2 className="text-3xl font-bold">文章管理</h2>
            <p className="text-muted-foreground">管理所有博客文章</p>
          </div>
        </div>
        <div className="text-center py-8">
          <p>加载中...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-3xl font-bold">文章管理</h2>
          <p className="text-muted-foreground">管理所有博客文章</p>
        </div>
        <Link href="/admin/posts/new">
          <Button>
            <Plus className="h-4 w-4 mr-2" />
            新建文章
          </Button>
        </Link>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>所有文章 ({posts.length})</CardTitle>
          <CardDescription>点击文章标题查看详情，或使用操作按钮进行编辑</CardDescription>
        </CardHeader>
        <CardContent>
          {posts.length === 0 ? (
            <div className="text-center py-12">
              <div className="text-muted-foreground mb-4">
                <FileText className="h-12 w-12 mx-auto" />
              </div>
              <h3 className="text-lg font-semibold mb-2">暂无文章</h3>
              <p className="text-muted-foreground mb-4">开始创建你的第一篇文章吧！</p>
              <Link href="/admin/posts/new">
                <Button>
                  <Plus className="h-4 w-4 mr-2" />
                  创建文章
                </Button>
              </Link>
            </div>
          ) : (
            <div className="space-y-4">
              {posts.map((post) => (
                <div key={post.id} className="flex items-center justify-between p-4 border rounded-lg hover:bg-muted/50 transition-colors">
                  <div className="flex-1 space-y-2">
                    <div className="flex items-center space-x-3">
                      <h3 className="font-semibold text-lg">{post.title}</h3>
                      <Badge variant={post.status === 'published' ? 'default' : 'secondary'}>
                        {post.status === 'published' ? '已发布' : '草稿'}
                      </Badge>
                    </div>
                    <p className="text-sm text-muted-foreground line-clamp-2">{post.excerpt}</p>
                    <div className="flex items-center space-x-4 text-xs text-muted-foreground">
                      <span>作者: {post.author}</span>
                      <span>创建: {formatDate(post.publishedAt)}</span>
                      <span>更新: {formatDate(post.updatedAt)}</span>
                      <div className="flex space-x-1">
                        {post.tags.slice(0, 3).map((tag) => (
                          <Badge key={tag} variant="outline" className="text-xs">
                            {tag}
                          </Badge>
                        ))}
                        {post.tags.length > 3 && (
                          <span className="text-xs">+{post.tags.length - 3}</span>
                        )}
                      </div>
                    </div>
                  </div>
                  <div className="flex items-center space-x-2">
                    <Link href={`/blog/${post.slug}`}>
                      <Button variant="ghost" size="sm">
                        <Eye className="h-4 w-4" />
                      </Button>
                    </Link>
                    <Link href={`/admin/posts/${post.id}/edit`}>
                      <Button variant="ghost" size="sm">
                        <Edit className="h-4 w-4" />
                      </Button>
                    </Link>
                    <DeleteConfirmDialog
                      onConfirm={() => handleDelete(post.id)}
                      title={post.title}
                      description={post.excerpt}
                      isLoading={deletingId === post.id}
                    />
                  </div>
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
